<!DOCTYPE html>

<html>

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>异步文件上传</title>

    <style type="text/css">
        .upload-component {
            border: 1px solid blue;
            width: 50%;
            margin: auto auto;
        }
        
        .file-input {
            width: 60%;
            margin-left: 15%;
            margin-top: 10px;
            border: 1px solid black;
            border-radius: 5px;
        }
    </style>
</head>

<body>

    <div class="upload-component">
        <input type="file" multiple class="input file-input">
        <input type="button" value="上传" class="input">
        <p class="tip" align="center"></p>
    </div>

    <script type="text/javascript">
        (() => {

            let clickListener = event => {
                event.stopPropagation();
                event.preventDefault();

                let target = event.target;
                let fileSelector = target.previousElementSibling;
                let tip = target.nextElementSibling;

                fileSelector.onchange = function() {
                    tip.innerHTML = ''
                }

                let files = fileSelector.files;
                console.log(files);
                if (files.length === 0) {
                    tip.innerHTML = '还没有选择任何文件';
                    tip.style.color = 'red'
                    return;
                }

                // 创建 FormData 实例
                let formData = new FormData();

                for (let i = 0; i < files.length; i++) {
                    let f = files[i];
                    console.log(f);
                    // 将被上传文件添加到 formData 中
                    formData.append('upfile', f);
                }

                console.log(formData);

                let $http = new XMLHttpRequest();

                let loadListener = () => {
                    console.log($http.readyState);
                    let r = JSON.parse($http.responseText);
                    tip.style.color = r.success ? 'blue' : 'red';
                    if (r.success) {
                        let input = document.querySelectorAll('.input');
                        input.forEach(e => {
                            e.style.display = 'none';
                        })
                    }
                    tip.innerHTML = r.message;
                }

                $http.addEventListener('load', loadListener, false);

                $http.open('post', '/upload');

                // 若发送的数据是以 FormData 形式存在的，
                // 则默认的 content-type 是 multipart/form-data
                $http.send(formData);

                // clickListener 结束
            }

            let btn = document.querySelector('input[type=button]');
            btn.addEventListener('click', clickListener, false);
        })();
    </script>

</body>

</html>